//
// Created by alexa on 5/13/2024.
//

#include "BattalionsService.h"
#include "../../exceptions/EntityNotFound.h"

Battalion *BattalionsService::getById(string id) {
    Battalion *battalion = repository.findById(id);
    if (!battalion) {
        throw EntityNotFound("Battalion with this ID wasn't found");
    }
    return battalion;
}

vector<Battalion *> BattalionsService::getAll() {
    return repository.findAll();
}

Battalion *BattalionsService::createOne(string name) {
    Battalion *battalion = new Battalion(name);
    saveBattalion(battalion);
    return battalion;
}

void BattalionsService::deleteOne(string id) {
    Battalion *battalion = getById(id);
    repository.deleteOne(battalion);
}

void BattalionsService::addCombatUnit(string battalionId, string unitId) {
    Battalion *battalion = getById(battalionId);
    CombatUnit *unit = unitsService->getById(unitId);
    battalion->addUnitId(unit->getId());
    saveBattalion(battalion);
}

void BattalionsService::removeCombatUnit(string battalionId, string unitId) {
    Battalion *battalion = getById(battalionId);
    CombatUnit *unit = unitsService->getById(unitId);
    battalion->removeUnitId(unit->getId());
    saveBattalion(battalion);
}


BattalionsService::BattalionsService(UnitsService *unitsService) : unitsService(unitsService) {}

vector<CombatUnit *> BattalionsService::getUnitsInBattalion(string battalionId) {
    Battalion *battalion = getById(battalionId);
    vector<CombatUnit *> units = unitsService->getManyByIds(battalion->getAllUnitsIds());
    return units;
}

Battalion *BattalionsService::findByUnitId(string unitId) {
    vector<Battalion *> allBattalions = getAll();
    for (const auto &battalion: allBattalions) {
        vector<string> ids = battalion->getAllUnitsIds();
        vector<string>::iterator id = find(ids.begin(), ids.end(), unitId);
        if (id != ids.cend()) return battalion;
    }
    return nullptr;
}

void BattalionsService::saveBattalion(Battalion *battalion) {
    repository.save(battalion);
}

